/*
 * @Author: soso
 * @Date: 2022-01-05 18:55:23
 * @LastEditTime: 2022-03-14 15:59:25
 * @LastEditors: Please set LastEditors
 * @Description: soso
 * @FilePath: /file-sync/config/node.go
 */
package config

import (
	"gomeshsync/pingpong"
	"io/ioutil"
	"log"
	"math/rand"
	"sync"

	"gitee.com/kimsoso/go-utils/utils"
	"gopkg.in/yaml.v3"
)

var (
	svrNodes  []string //节点列表
	onceNodes sync.Once
)

// 得到所有客户端地址
func GetNodes() []string {
	c := GetConfig()
	if !c.AutoNodes {
		onceNodes.Do(func() {
			ReloadNodes()
		})
		return svrNodes
	} else {
		return pingpong.NewPingpong(PathOfNodes).GetNodes()
	}
}

/**
 * 取得主机地址
 */
func GetNextNode() string {
	nodes := GetNodes()
	if len(nodes) == 0 {
		return ""
	}

	localIP := utils.GetLocalIPOnce()

	if len(nodes) == 1 && nodes[0] == localIP {
		return ""
	}

	for {
		node := nodes[rand.Intn(len(nodes))]
		if localIP != node {
			return node
		}
	}
}

func ReloadNodes() {
	c := GetConfig()
	fileContent, _ := ioutil.ReadFile(c.NodesFile)
	nodes := []string{}
	err := yaml.Unmarshal(fileContent, &nodes)
	if err == nil {
		log.Println("nodes file is loaded")
		svrNodes = nodes
	} else {
		log.Println("load nodes error", err)
	}
}
